#include "mythread.hpp"
#include "LockGuard.hpp"
#include <iostream>
#include <unistd.h>
#include <string>
#include <vector>
#include <cstdio>
using namespace ThreadClass;
/*---互斥锁---*/
const int N = 5;
/*--总票数--*/
int tickets = 1000;
/*---全局互斥锁---*/
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// void threadRun(ThreadData* td)
// {
//     while (true)
//     {
//         /*--加锁--*/
//         pthread_mutex_lock(td->GetLock());
//         if (tickets > 0)
//         {
//             usleep(1000);
//             printf("who: %s,shell ticket = %d\n", td->GetName().c_str(), tickets);
//             --tickets;
//             /*--解锁--*/
//             pthread_mutex_unlock(td->GetLock());
//         }
//         else
//         {
//             /*--解锁--*/
//             pthread_mutex_unlock(td->GetLock());
//             break;
//         }
//     }
// }
void threadRun(ThreadData* td)
{
    while (true)
    {
        /*--加锁--*/
        LockGuard lock(td->GetLock());//RAII原理的锁
        if (tickets > 0)
        {
            usleep(1000);
            printf("who: %s,shell ticket = %d\n", td->GetName().c_str(), tickets);
            --tickets;
        }
        else
        {
            break;
        }
    }
}
void ThreadWork()
{
    std::vector<Thread> threads;
    /*---局部互斥锁---*/
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
    for (int i = 0; i < N; i++)
    {
        std::string threadName = std::string("thead-") + std::to_string(i + 1);
        ThreadData* td = new ThreadData(threadName,&mutex);
        threads.emplace_back(threadRun,td);
    }
    for (auto &thread : threads)
    {
        thread.Start();
    }
    for (auto &thread : threads)
    {
        thread.Join();
    }
    pthread_mutex_destroy(&mutex);
}
int main()
{
    ThreadWork();
    return 0;
}
